package cn.elead.chaos.sso.server.web.system.controller;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.elead.chaos.core.enums.BusinessType;
import cn.elead.chaos.framework.monitor.operlog.Log;
import cn.elead.chaos.framework.web.global.ApiAssert;
import cn.elead.chaos.framework.web.global.ErrorCodeEnum;
import cn.elead.chaos.framework.web.global.response.UnifiedReturn;
import cn.elead.chaos.mybatils.web.controller.BaseController;
import cn.elead.chaos.shiro.util.ShiroUtils;
import cn.elead.chaos.sso.server.constants.UserConstants;
import cn.elead.chaos.sso.server.web.system.domain.SysDept;
import cn.elead.chaos.sso.server.web.system.domain.SysRole;
import cn.elead.chaos.sso.server.web.system.domain.Ztree;
import cn.elead.chaos.sso.server.web.system.service.ISysDeptService;
import cn.hutool.core.util.ObjectUtil;

/**
 * 部门信息
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {
	private String prefix = "system/dept";

	@Autowired
	private ISysDeptService deptService;

	@RequiresPermissions("system:dept:view")
	@GetMapping()
	public String dept() {
		return prefix + "/dept";
	}

	@ResponseBody
	@UnifiedReturn
	@PostMapping("/list")
	@RequiresPermissions("system:dept:list")
	public List<SysDept> list(SysDept dept) {
		List<SysDept> deptList = deptService.selectDeptList(dept);
		return deptList;
	}

	/**
	 * 新增部门
	 */
	@GetMapping("/add/{parentId}")
	public String add(@PathVariable("parentId") Long parentId, ModelMap mmap) {
		mmap.put("dept", deptService.selectDeptById(parentId));
		return prefix + "/add";
	}

	/**
	 * 新增保存部门
	 */
	@ResponseBody
	@PostMapping("/add")
	@Log(title = "部门管理", businessType = BusinessType.INSERT)
	@RequiresPermissions("system:dept:add")
	public void addSave(@Validated SysDept dept) {
		if (UserConstants.DEPT_NAME_NOT_UNIQUE == deptService.checkDeptNameUnique(dept)) {
			ApiAssert.failure(ErrorCodeEnum.BAD_REQUEST.convert("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在"));
		}
		dept.setCreateBy(ShiroUtils.getLoginName());
		deptService.insertDept(dept);
	}

	/**
	 * 修改
	 */
	@GetMapping("/edit/{deptId}")
	public String edit(@PathVariable("deptId") Long deptId, ModelMap mmap) {
		SysDept dept = deptService.selectDeptById(deptId);
		if (ObjectUtil.isNotNull(dept) && 100L == deptId) {
			dept.setParentName("无");
		}
		mmap.put("dept", dept);
		return prefix + "/edit";
	}

	/**
	 * 保存
	 */
	@Log(title = "部门管理", businessType = BusinessType.UPDATE)
	@RequiresPermissions("system:dept:edit")
	@PostMapping("/edit")
	@ResponseBody
	public void editSave(@Validated SysDept dept) {
		if (UserConstants.DEPT_NAME_NOT_UNIQUE == deptService.checkDeptNameUnique(dept)) {
			ApiAssert.failure(ErrorCodeEnum.BAD_REQUEST.convert("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在"));
		} else if (dept.getParentId().equals(dept.getDeptId())) {
			ApiAssert.failure(ErrorCodeEnum.BAD_REQUEST.convert("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己"));
		}
		dept.setUpdateBy(ShiroUtils.getLoginName());
		deptService.updateDept(dept);
	}

	/**
	 * 删除
	 */
	@ResponseBody
	@GetMapping("/remove/{deptId}")
	@Log(title = "部门管理", businessType = BusinessType.DELETE)
	@RequiresPermissions("system:dept:remove")
	public void remove(@PathVariable("deptId") Long deptId) {
		if (deptService.selectDeptCount(deptId) > 0) {
			ApiAssert.failure(ErrorCodeEnum.BAD_REQUEST.convert("存在下级部门,不允许删除"));
		}
		if (deptService.checkDeptExistUser(deptId)) {
			ApiAssert.failure(ErrorCodeEnum.BAD_REQUEST.convert("部门存在用户,不允许删除"));
		}
		deptService.deleteDeptById(deptId);
	}

	/**
	 * 校验部门名称
	 */
	@ResponseBody
	@PostMapping("/checkDeptNameUnique")
	public int checkDeptNameUnique(SysDept dept) {
		return deptService.checkDeptNameUnique(dept);
	}

	/**
	 * 选择部门树
	 */
	@GetMapping("/selectDeptTree/{deptId}")
	public String selectDeptTree(@PathVariable("deptId") Long deptId, ModelMap mmap) {
		mmap.put("dept", deptService.selectDeptById(deptId));
		return prefix + "/tree";
	}

	/**
	 * 加载部门列表树
	 */
	@ResponseBody
	@UnifiedReturn
	@GetMapping("/treeData")
	public List<Ztree> treeData() {
		List<Ztree> ztrees = deptService.selectDeptTree(new SysDept());
		return ztrees;
	}

	/**
	 * 加载角色部门（数据权限）列表树
	 */
	@ResponseBody
	@GetMapping("/roleDeptTreeData")
	public List<Ztree> deptTreeData(SysRole role) {
		List<Ztree> ztrees = deptService.roleDeptTreeData(role);
		return ztrees;
	}
}
